package com.zrb.mobile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

//import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zrb.applib.utils.AppSetting;
import com.zrb.mobile.adapter.Discover_listAdapter;
import com.zrb.mobile.adapter.UserMyFindMoneyAdapter;
import com.zrb.mobile.adapter.UserMyMessageAdapter;
import com.zrb.mobile.adapter.model.FocusDto;
import com.zrb.mobile.adapter.model.IndustrydistributDto;
import com.zrb.mobile.adapter.model.MyMessageDto;
import com.zrb.mobile.adapter.model.UserMyFindMoneyDto;
import com.zrb.mobile.adapter.model.UserMyMessageDto;
import com.zrb.mobile.pulltorefresh.PullToRefreshBase;
import com.zrb.mobile.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.zrb.mobile.ui.PullToRefreshListViewEx;
import com.zrb.mobile.ui.onLoadMoreListener;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.Constants;
import com.zrb.mobile.utility.DialogBuilder;
import com.zrb.mobile.utility.MsgformatUtil;
import com.zrb.mobile.utility.ZrbRestClient;
import com.zrb.mobile.utility.ZrbRestClient.HttpResponseListener;

public class User_my_message extends BaseActivity implements OnClickListener,
		OnItemClickListener, onLoadMoreListener {

	UserMyMessageAdapter userMyFindMoneyAdapter;
	private PullToRefreshListViewEx listview;
	// private List<Intention> list;
	// int curPageindex=0;
	int currentPage;
	Handler myhandler = new Handler();
	Dialog AuthDialog;
	// private long maxId = 1;
	// public String ACTION_NAME_THREE = "my_findmoney";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.message_home_activity1);
		// registerBoradcastReceiver1();
		initView();
		myhandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				listview.setRefreshing(true);
			}
		}, 200);
	}

	/**
	 * 初始化UI
	 */
	private void initView() {

		View v = findViewById(R.id.include_top);
		((TextView) v.findViewById(R.id.txt_title)).setText("我的消息");
		View lefticon = this.findViewById(R.id.title_left_root);
  		
		lefticon.setOnClickListener(this);
		View txtBtn=this.findViewById(R.id.btn_callserver);
		txtBtn.setVisibility(View.VISIBLE);
		txtBtn.setOnClickListener(this);;
		
		listview = (PullToRefreshListViewEx) findViewById(R.id.discover_list_view);
		listview.setPagesize(14);
		
		listview.setOnItemClickListener(this);// 点击事件
		listview.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(
						CommonUtil.getcurTime(User_my_message.this));
				currentPage = 1;
				myhandler.postDelayed(new Runnable() {
					@Override
					public void run() {
						LoadData(-1, true);
					}
				}, 1000);
			}
		});

		userMyFindMoneyAdapter = new UserMyMessageAdapter(this,
				new ArrayList<MyMessageDto>());
		listview.initAdapter(userMyFindMoneyAdapter);
		listview.setOnLoadMoreListener(this);
		// listview.setAdapter(usermyPublishAdapter);
	}

	@Override
	public void OnLoadMoreEvent() {
		// TODO Auto-generated method stub
		currentPage++;
		myhandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				LoadData(userMyFindMoneyAdapter.getMinId(), false);
			}
		}, 300);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_left_root:
			this.finish();
			break;
		case R.id.btn_callserver:
			callServerPhone();
			break;
		}
	}
	public void callServerPhone() {
		DialogBuilder builder2 = new DialogBuilder(User_my_message.this);
		// builder2.setTheme(Resource.Style.customDialog);
		builder2.setParentlayout(R.layout.custom_ucenter_dialog);
		builder2.setContentView(R.layout.u_center_org_auth); // ac_dialog_cancel;
		builder2.setPositiveTitle("呼叫");
		TextView hitetxt = (TextView) builder2.getCurContentView().findViewById(R.id.tv_authstr);
//		String msource = this.getResources().getString(
//				R.string.user_center_profile_edit_org_authtrue1);
//		hitetxt.setText(msource);
		hitetxt.setText(Constants.serverPhone);
		builder2.setCloseOnclick(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				AuthDialog.dismiss();
				if (arg0.getId() == R.id.btn_confirm) {
					Intent intent = new Intent(Intent.ACTION_CALL, Uri
							.parse("tel:" + Constants.serverPhone));// "400-688-0101"
					User_my_message.this.startActivity(intent);
				}
			}
		});
		AuthDialog = builder2.create();
		AuthDialog.show();
	}
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		MyMessageDto intention = userMyFindMoneyAdapter.list1.get(position - 1);
		// 当消息状态未读的时候，去执行信息状态栏改变
		if (intention.read == 0) {
			MakeRead(intention.id, position - 1);
		}
		
		Intent intent = MsgformatUtil.getQuickAction(User_my_message.this,intention);
		startActivity(intent);  
		
		// if (null != intention.messageInfo.bizKey
		// && !"".equals(intention.messageInfo.bizKey)) {
		// String type = StringUtils.substringAfter(
		// intention.messageInfo.bizKey, ":");
		// if ("101".equals(type)) {
		// // 跳转到项目
		// Intent intent = new Intent(User_my_message.this,
		// ProjectDetailActivity.class);
		// intent.putExtra("id", intention.messageInfo.id);
		// intent.putExtra("title", "项目详情");
		// startActivity(intent);
		// } else if ("102".equals(type)) {
		// // 跳转到资金
		// Intent intent = new Intent(User_my_message.this,
		// MoneyDetailActivity.class);
		// intent.putExtra("id", intention.messageInfo.id);
		// intent.putExtra("title", "资金详情");
		// startActivity(intent);
		// }

		// }
		// Intent intent = new Intent(User_my_message.this,
		// MoneyDetailActivity.class);
		// MyMessageDto myFindMoney = userMyFindMoneyAdapter.list1
		// .get(position - 1);
		// intent.putExtra("id", new Long(myFindMoney.id).intValue());
		// intent.putExtra("title", myFindMoney.title);
		// startActivity(intent);

		// Toast.makeText(this, "点击事件", 0).show();
	}

	ZrbRestClient mZrbRestClient;
	private void LoadData(long maxId, final boolean isreflesh) {
		RequestParams param = new RequestParams();
		//param.put("zrb_front_ut", AppSetting.curUser.zrb_front_ut);
		param.put("limit", 14);
		if (-1 != maxId) {
			param.put("maxId", maxId);
		}

		
		CommonUtil.InfoLog("message/queryMessage", param.toString());
		if(null==mZrbRestClient){
			
			mZrbRestClient=new ZrbRestClient(this);
			mZrbRestClient.setOnhttpResponseListener(new HttpResponseListener() {
				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
					CommonUtil.showToast(arg0, User_my_message.this);
					if (currentPage > 1)
						listview.hideloading();
					else
						listview.onRefreshComplete();
				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// loadingview.Hide();
					String results = new String(arg2);
					// CommonUtil.InfoLog("intention/list", results);
					if (currentPage == 1)
						listview.onRefreshComplete();
					else
						listview.hideloading();
					try {
						Gson gson = new Gson();
						UserMyMessageDto tmpDto = gson.fromJson(results, UserMyMessageDto.class);
						if (tmpDto.res == 1) {

							if (tmpDto.data != null && tmpDto.data.size() > 0) {
								if (currentPage == 1) {
									userMyFindMoneyAdapter.setCurDatas(tmpDto.data);
								} else {
									userMyFindMoneyAdapter.addAll(tmpDto.data);
								}
								userMyFindMoneyAdapter.notifyDataSetChanged();
							} else {
								CommonUtil.showToast(String.format("暂无%1$s信息~~", currentPage == 1 ? "": "更多"),
										           User_my_message.this);
	 						}
						} else
							CommonUtil.showToast(tmpDto.msg,User_my_message.this);
					} catch (Exception e) {
						CommonUtil.showToast(R.string.error_serverdata_loadfail,User_my_message.this);
					}
				}
			});
		}
		mZrbRestClient.post("message/queryMessage", param);
	}

	// 点击阅读
	private void MakeRead(long id, final int position) {
		RequestParams param = new RequestParams();
		// param.put("content", content);
		param.put("id", id);
		param.put("zrb_front_ut", AppSetting.curUser.zrb_front_ut);
		CommonUtil.InfoLog("param", param.toString());
		ZrbRestClient.post("message/readMessage", param,
				new AsyncHttpResponseHandler() {
					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						CommonUtil.showToast(User_my_message.this
								.getString(R.string.error_net_loadfail),
								User_my_message.this);
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						String results = new String(arg2);
						try {
							Gson gson = new Gson();
							FocusDto tmpDto = gson.fromJson(results,
									FocusDto.class);
							if (tmpDto.res == 1) {
								if (tmpDto.data) {
									userMyFindMoneyAdapter.list1.get(position).read = 1;
									userMyFindMoneyAdapter
											.notifyDataSetChanged();
								}

							} else {
								CommonUtil.showToast(tmpDto.msg,
										User_my_message.this);
							}
						} catch (Exception e) {
							// loadingview.HideText(e.getMessage()).ShowRefleshBtn(true).ShowError();
							CommonUtil.showToast(
									User_my_message.this
											.getString(R.string.error_serverdata_loadfail),
									User_my_message.this);
						}

					}
				});
	}
	/*
	 * @Override protected void onDestroy() { // TODO Auto-generated method stub
	 * super.onDestroy(); unregisterReceiver(mBroadcastReceiver1); }
	 * 
	 * public void registerBoradcastReceiver1() { IntentFilter myIntentFilter =
	 * new IntentFilter(); myIntentFilter.addAction(ACTION_NAME_THREE); // 注册广播
	 * registerReceiver(mBroadcastReceiver1, myIntentFilter); }
	 * 
	 * private BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
	 * 
	 * @Override public void onReceive(Context context, Intent intent) { String
	 * action = intent.getAction(); if (action.equals(ACTION_NAME_THREE)) { int
	 * position = intent.getIntExtra("position", -1); addCount(position); } } };
	 * 
	 * protected void addCount(int position) { // int position =
	 * data.getIntExtra("position", -1); // TODO Auto-generated method stub
	 * userMyFindMoneyAdapter.list1.get(position).queryNum =
	 * userMyFindMoneyAdapter.list1 .get(position).queryNum + 1;
	 * userMyFindMoneyAdapter.notifyDataSetChanged(); }
	 */

}
